/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.freedoit.common.util;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 *
 * @author wanglei
 */
public class SqlTimestampTypeAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp>{
	private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public JsonElement serialize(Timestamp src, Type arg1, JsonSerializationContext arg2) {
		String dateFormatAsString = format.format(src);
		return new JsonPrimitive(dateFormatAsString);
	}

	public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            if (!(json instanceof JsonPrimitive)) {
                    throw new JsonParseException("The date should be a string value");
            }

            try {
                java.util.Date date = format.parse(json.getAsString());
                return new Timestamp(date.getTime());
            } catch (ParseException e) {
                throw new JsonParseException(e);
            }
	}

}
